'use strict';

const Service = require('egg').Service;

class SystemPermissionService extends Service {
    async getUserRoles(userId) {
        if (!userId) {
            return [];
        }
        const result = await this.ctx.model.System.SystemUserRole.findAll({
            where: {
                user_id: userId
            },
            attributes: ['role_id'],
            raw: true
        });
        return result.map(item => item.role_id);
    }

    async updateUserRoles(userId, roleIds) {
        if (!userId) {
            return [];
        }
        // 事务
        const transaction = await this.ctx.model.transaction();
        try {
            await this.ctx.model.System.SystemUserRole.destroy({
                where: {
                    user_id: userId
                },
                transaction
            });
            for (let i = 0; i < roleIds.length; i++) {
                await this.ctx.model.System.SystemUserRole.create({
                    roleId: roleIds[i],
                    userId,
                    creator: this.ctx.user.id,
                    updater: this.ctx.user.id,
                }, {
                    transaction
                })
            }
            await transaction.commit();
            return true
        }
        catch (e) {
            await transaction.rollback();
            throw e
        }
    }


    async listRoleMenus(roleId) {
        if (!roleId) {
            return [];
        }
        const result = await this.ctx.model.System.SystemRoleMenu.findAll({
            where: {
                role_id: roleId
            },
            attributes: ['menu_id'],
            raw: true
        });
        return result.map(item => item.menu_id);
    }

    async updateRoleMenus(roleId, menuIds) {
        if (!roleId) {
            return [];
        }
        // 事务
        const transaction = await this.ctx.model.transaction();
        try {
            await this.ctx.model.System.SystemRoleMenu.destroy({
                where: {
                    role_id: roleId
                },
                transaction
            });
            for (let i = 0; i < menuIds.length; i++) {
                await this.ctx.model.System.SystemRoleMenu.create({
                    roleId,
                    menuId: menuIds[i],
                    creator: this.ctx.user.id,
                    updater: this.ctx.user.id,
                }, {
                    transaction
                }
                )
            }
            await transaction.commit();
            return true
        }
        catch (e) {
            await transaction.rollback();
            throw e
        }
    }
}

module.exports = SystemPermissionService;
